package com.okilo.online.app.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.View
import com.okilo.online.app.R
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.databinding.OkiloActProcessStepsBinding
import com.okilo.online.app.databinding.OkiloActProcessStepsTitleBinding
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.tools.OkiloPickCntUtils
import com.okilo.online.app.tools.OkiloTitleBarUtil
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.helper.OkiloConfigProcessHp
import com.okilo.online.app.fmt.OkiloStepContactFmt
import com.okilo.online.app.fmt.OkiloStepGeneralFmt
import com.okilo.online.app.pet.OkiloProcessPet
import com.okilo.online.app.pet.view.IOkiloProcess
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/18 18:51
 * @Annotation：进件流程
 */
open class OkiloProcessStepsAct: OkiloComAct(), IOkiloProcess {
    private var _binding: OkiloActProcessStepsBinding? = null

    //选择联系人
    var pickContact: OkiloPickCntUtils? = null

    private var okiloProcessPet: OkiloProcessPet? = null

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, OkiloProcessStepsAct::class.java)
            context.startActivity(intent)
        }
    }

    override var pageName: String = ""

    override val enablePageTrack: Boolean = false

    override fun createOkiloContentView(): View? {
        _binding = OkiloActProcessStepsBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeOkiloViews() {
        OkiloTitleBarUtil.setStatusBarLightMode(this, true)
        getTitleBarManager()
            .setTitleBarVisibility(View.VISIBLE)
            .setTitle(getString(R.string.okilo_process_steps_title))
            .setRootBackgroundColor(getColor(R.color.okilo_color_ffeff1f3))
        pickContact = OkiloPickCntUtils(this)
    }

    override fun setupOkiloEventListeners() {
        super.setupOkiloEventListeners()
        //提交
        _binding?.okiloProcessStepButtonNext?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_PROCESS_STEP_SUBMIT))
            }
        })
    }

    override fun loadOkiloData() {
        gOkiloProgressStepsData()
    }

    /**
     * 所有步骤已完成 - 进入申贷页
     */
    private fun sOkiloProcessStepCompleteViews() {
        OkiloApplyAct.start(this)
        finish()
    }

    /**
     * 移除所有步骤
     */
    private fun removeOkiloProcessStepAllViews() {
        _binding?.processCurrentLayout?.removeAllViews()
    }

    /**
     * 设置认证步骤进度
     */
    @SuppressLint("SetTextI18n")
    fun sOkiloProcessStepProgress(stepTitleList: ArrayList<String>, index: Int) {
        _binding?.okiloProcessFinishedLayout?.removeAllViews()
        _binding?.okiloProcessUnfinishedLayout?.removeAllViews()

        // 设置可见性
        _binding?.okiloProcessFinishedLayout?.visibility = if (index > 0) View.VISIBLE else View.GONE
        _binding?.okiloProcessUnfinishedLayout?.visibility = if (index < stepTitleList.size - 1) View.VISIBLE else View.GONE

        stepTitleList.forEachIndexed { position, title ->
            val titleBinding = OkiloActProcessStepsTitleBinding.inflate(layoutInflater)
            titleBinding.okiloProcessStepTitle.text = "${position + 1}.$title"
            if (position < index){
                titleBinding.okiloProcessStepStatusIcon.setImageResource(R.mipmap.okilo_process_step_finished_icon)
                _binding?.okiloProcessFinishedLayout?.addView(titleBinding.root)
            } else if (position > index){
                titleBinding.okiloProcessStepStatusIcon.setImageResource(R.mipmap.okilo_process_step_unfinished_icon)
                _binding?.okiloProcessUnfinishedLayout?.addView(titleBinding.root)
            }
        }

        _binding?.okiloProcessStepSubmitSuccessTipsText?.visibility = View.GONE
        _binding?.okiloProcessStepSubmitSuccessTipsIcon?.visibility = View.GONE
    }

    /**
     * 联系人
     */
    private fun sOkiloProcessStepPhoneBookView(data: JSONObject) {
        getFragmentNavigator().replaceFragment(
            R.id.processCurrentLayout,
            OkiloStepContactFmt(this, data)
        )

        sOkiloProcessStepSubmitSuccessApprovedTips()
    }

    /**
     * 通用样式
     */
    private fun sOkiloProcessStepGeneralView(data: JSONObject) {
        getFragmentNavigator().replaceFragment(R.id.processCurrentLayout, OkiloStepGeneralFmt(data))

        //个人信息
        if (pageName == "personal_info"){
            sOkiloProcessStepSubmitSuccessApprovedTips()
        }
    }

    /**
     * 显示提交完成通过率提示
     */
    private fun sOkiloProcessStepSubmitSuccessApprovedTips(){
        val showApprovedKey1 = getString(R.string.okilo_process_steps_submit_success_approved_tips_rate)
        val showApprovedText = String.format(getString(R.string.okilo_process_steps_submit_success_approved_tips),showApprovedKey1)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.okilo_color_fff25800)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.okiloProcessStepSubmitSuccessTipsText?.text = approvedTipsSpannable
        _binding?.okiloProcessStepSubmitSuccessTipsText?.visibility = View.VISIBLE
        _binding?.okiloProcessStepSubmitSuccessTipsIcon?.visibility = View.VISIBLE
    }

    /**
     * 提交
     */
    open fun sOkiloProcessStepSubmitAction(params: JSONObject){
        sOkiloProcessStepAction(params)
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    override fun sOkiloProcessSubmitCallback() {
        //通知刷新总流程
        publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_PROCESS_REFRESH))
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        when(event.eventType){
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESHED -> {
                hideOkiloLoading()
                gOkiloProgressStepsData()
            }
            else -> {

            }
        }
    }

    /**
     * 加载流程步骤
     */
    private fun gOkiloProgressStepsData(){
        removeOkiloProcessStepAllViews()

        val allStepTitles = OkiloConfigProcessHp.gOkiloConfigProcessAllStepTitleList()
        //当前进行的步骤
        val curtIndex = OkiloConfigProcessHp.gOkiloConfigProcessStepIndex()
        val allSteps = OkiloConfigProcessHp.gOkiloConfigProcessAllStepList()
        if (curtIndex == allSteps.size){//所有步骤已完成
            sOkiloProcessStepCompleteViews()
            return
        }
        val showTitle = "${curtIndex+1}.${allStepTitles[curtIndex]}"
        sOkiloProcessStepProgress(allStepTitles,curtIndex)

        val processData = OkiloConfigProcessHp.gOkiloConfigProcessData()
        pageName = allSteps[curtIndex]

        //获取对应的key
        val curtKey = allSteps[curtIndex]
        //todo Contact 类型
        if (processData != null && processData.has(curtKey)){
            val stepData = processData.optJSONObject(curtKey)
            stepData?.put("showTitle",showTitle)
            stepData?.put("stepTitle",pageName)
            if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                sOkiloProcessStepPhoneBookView(stepData)
                return
            }
        }

        //常规通用样式
        if (processData != null && processData.has(curtKey)){
            val stepData = processData.optJSONObject(curtKey)
            if (stepData != null) {
                stepData.put("showTitle",showTitle)
                stepData.put("stepTitle",pageName)
                sOkiloProcessStepGeneralView(stepData)
            }
        }
    }

    /**
     * 提交数据
     */
    private fun sOkiloProcessStepAction(params: JSONObject){
        showOkiloLoading()
        if (okiloProcessPet == null){
            okiloProcessPet = OkiloProcessPet(this)
        }
        okiloProcessPet?.subOkiloProcessRequest(params)
    }

    override fun onStop() {
        super.onStop()
        _binding?.root?.clearFocus()
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}